//
//  AppAssetsManager.swift
//  zhonglb_iOS
//
//  Created by lxm on 2022/5/19.
//

import Foundation
import Kingfisher
import UIKit

enum AppAssetsImageKey : String {
    // 首页黄金入口图
    case imgGoldhome = "goldhome"
    // 个人中心vip开通图片
    case overviewVip = "overviewVip"
    // 首页树苗图
    case treeHome = "treeHome"
    // 幸运bbxo背景
    case luckBlindBg = "luckBlindBg"
    // 幸运bbxo背景-等待
    case luckBlindBgWait = "luckBlindBgWait"
    // 超值背景
    case valueBoxBg = "valueBoxBg"
    // 开会员bg
    case blindVipPop = "blindVipPop"
    //
    case blindVipBgBtn = "blindVipBgBtn"
    // 抢
    case robBoxBg = "robBoxBg"
    // 充值按钮
    case robChargeBg = "robChargeBg"
    
    case autoRobBg = "autoRobBg"
    
    case boxPlaceHolder = "boxPlaceHolder"
    // 弹窗title
    case blindBoxTitle = "blindBoxTitle"
    /// 合伙人招募
    case HHRZM = "HHRZM"
    /// 区级合伙人
    case QJHHR = "QJHHR"
    /// 市级合伙人
    case SJHHR = "SJHHR"
    /// 省级合伙人
    case PJHHR = "PJHHR"
    /// 区域合伙人BG
    case QJHHR_BG = "QJHHR_BG"
    /// 市级合伙人BG
    case SJHHR_BG = "SJHHR_BG"
    /// 省级合伙人BG
    case PJHHR_BG = "PJHHR_BG"
    /// 申请服务商
    case APPLY_SERVICE_BG = "APPLY_SERVICE_BG"
}

class AppAssetsManager {
    let cacheKey = "AppAssetsManager_introImageAssets"
    
    private init(){
        if let json = UserDefaults.standard.object(forKey: cacheKey) as? String, let data = [IntroImageAssets].deserialize(from: json) {
            self.setIntroImageAssets(data: data.compactMap({$0}), needCache: false)
        }
    }
    
    // 介绍图片说明
    private var introImageAssets = [IntroImageAssets]()
    
    func setIntroImageAssets(data : [IntroImageAssets], needCache : Bool) {
        introImageAssets = data
        introImageAssets.forEach { m in
            let key = m.key != "" ? m.key : "\(m.type)"
            introImageAssetsMap[key] = m
        }
        preloadImg()
        if needCache {
            let json = introImageAssets.toJSONString()
            UserDefaults.standard.set(json, forKey: cacheKey)
        }
    }
    
    var introImageAssetsMap = [String : IntroImageAssets]()
    
    static let share = AppAssetsManager()
    
    // 升级背景前缀
    let lEVEL_UP_BGPREFIX = "LUB_"
    
    // 升级成功背景前缀
    let lEVEL_UP_SUCCESS_BGPREFIX = "LUB_SUCCESS_"

    //MARK: 获取介绍图片
    func getIntroUrl(type : Int) -> String? {
       return self.introImageAssets.first(where: {$0.type == type})?.url
    }
    
    //MARK: 获取升级背景图
    func getLevelUpBg(_ key : String) -> String? {
        return introImageAssetsMap[lEVEL_UP_BGPREFIX + key]?.url
    }
    
    //MARK: 获取升级背景图
    func getLevelUpSuccessBg(_ key : String) -> String? {
        return introImageAssetsMap[lEVEL_UP_SUCCESS_BGPREFIX + key]?.url
    }
    
    //MARK: 通过key获取图片
    func getImg(_ key : String) -> String? {
        return introImageAssetsMap[key]?.url
    }
    
    func preloadImg() {
        if AppHelper.appVerify() {return}
        introImageAssets.forEach { m in
            if let url = URL.init(string: m.url) {
                if KingfisherManager.shared.cache.diskStorage.isCached(forKey: m.url) == false{
                    KingfisherManager.shared.downloader.downloadImage(with: url, options: []) { r in
                        switch r {
                        case .success(let img):
                            KingfisherManager.shared.cache.store(img.image, forKey: m.url)
                            XMLogger.info("缓存图片成功----\(m.url))")
                        case .failure(let _):
                            XMLogger.error("缓存载图片失败----\(m.url)")
                        }
                    }
                } else {
                    XMLogger.info("已经缓存----\(m.url))")
                }
            }
        }
    }
    
    func imageResultSize(_ width : CGFloat, img : UIImage) -> CGSize {
        let height = width / img.size.width * img.size.height
        return CGSize(width: width, height: height)
    }
}

//
struct IntroImageAssets : HandyJSON {
    var id = 0
    var url = ""
    //资源类型:1.飞机票图片说明, 2.数字NFR介绍图, 3余额转背包说明, 4.普通vip说明 5.超级vip说明
    var type = 0
    
    var key = ""
}

//MARK: VIP信息
struct VIPInfo: HandyJSON {
    var avatar = ""
    // 0未到期, 1已到期
    var invalidStatus = 1
    //vip到期时间
    var invalidVipTime = ""
    
    var nickName: String!
    // 0未开通, 1已开通
    var vipStatus: Int = 0
    // 0普通vip 1超级vip
    var vipType: Int = 0
}

//MARK: imageView 扩展
extension ZM where Base : UIImageView {
    func assetSetImg(key : AppAssetsImageKey, placeholder : String? = nil, options : KingfisherOptionsInfo? = nil, completionHandler : ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) {
        let img = AppAssetsManager.share.getImg(key.rawValue)
        base.zm.setImage(urlStr: img ?? "", placeholder: placeholder, options: options, completionHandler : completionHandler)
    }
}

//MARK: UIButton 扩展
extension ZM where Base : UIButton {
    func assetImage(key : AppAssetsImageKey , state: UIControl.State, placeholder : String? = nil,options : KingfisherOptionsInfo? = nil) {
        let img = AppAssetsManager.share.getImg(key.rawValue)
        base.zm.setImage(urlStr: img ?? "", state: state, placeholder: placeholder, options:options)
    }
}
